<template>
  <div class="common-container">
    <div class="common-header">
      <h2>客户管理</h2>
    </div>
    
    <!-- 查询条件和操作按钮 -->
    <div class="common-search-bar">
      <el-form :inline="true" :model="queryForm" class="common-search-form">
        <el-form-item label="客户状态">
          <el-select 
            v-model="queryForm.status" 
            placeholder="请选择客户状态" 
            clearable
            style="width: 150px;"
          >
            <el-option label="全部" value="" />
            <el-option label="潜在客户" value="潜在客户" />
            <el-option label="已联系客户" value="已联系客户" />
            <el-option label="已流失" value="已流失" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input 
            v-model="queryForm.keyword" 
            placeholder="客户姓名或公司名称" 
            clearable
            style="width: 200px;"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="customersLoading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item style="margin-left: auto;">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增客户
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-card class="common-table-card">
      <el-table 
        :data="customers" 
        style="width: 100%;" 
        v-loading="customersLoading"
        :height="tableHeight"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="客户姓名" min-width="120" />
        <el-table-column prop="companyName" label="公司名称" min-width="150" />
        <el-table-column label="联系方式" min-width="180">
          <template #default="scope">
            <div>
              <div v-if="scope.row.phone">电话：{{ scope.row.phone }}</div>
              <div v-if="scope.row.email">邮箱：{{ scope.row.email }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="客户状态" width="120">
          <template #default="scope">
            <el-tag 
              :type="getStatusTagType(scope.row.status)"
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="来源" width="120" />
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column prop="creatorName" label="创建人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="common-pagination">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          small
        />
      </div>
    </el-card>
    
    <!-- 客户编辑/新增对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="600px"
      @close="resetForm"
    >
      <el-form 
        ref="customerFormRef" 
        :model="customerForm" 
        :rules="customerFormRules" 
        label-width="100px"
      >
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="客户姓名" prop="name">
              <el-input v-model="customerForm.name" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="customerForm.companyName" placeholder="请输入公司名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="customerForm.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系邮箱" prop="email">
              <el-input v-model="customerForm.email" placeholder="请输入联系邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="客户状态" prop="status">
              <el-select v-model="customerForm.status" placeholder="请选择客户状态" style="width: 100%;">
                <el-option label="潜在客户" value="潜在客户" />
                <el-option label="已联系客户" value="已联系客户" />
                <el-option label="已流失" value="已流失" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源">
              <el-input v-model="customerForm.source" placeholder="如：官网咨询、朋友推荐" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input 
            v-model="customerForm.remark" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="common-dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { getCustomerList, createCustomer, updateCustomer, deleteCustomer } from '../utils/api'

export default {
  name: 'CustomerManagement',
  components: {
    Plus,
    Search
  },
  setup() {
    const customers = ref([])
    const customersLoading = ref(false)
    const dialogVisible = ref(false)
    const submitLoading = ref(false)
    const isEdit = ref(false)
    const customerFormRef = ref()
    
    // 查询表单
    const queryForm = ref({
      status: '',
      keyword: ''
    })
    
    // 分页数据
    const pagination = ref({
      page: 1,
      size: 10,
      total: 0
    })
    
    // 计算表格高度
    const tableHeight = computed(() => {
      return 'calc(100vh - 284px)'
    })
    
    const customerForm = ref({
      id: null,
      name: '',
      companyName: '',
      phone: '',
      email: '',
      status: '',
      source: '',
      remark: ''
    })
    
    // 自定义验证规则
    const validateContact = (rule, value, callback) => {
      if (!customerForm.value.phone && !customerForm.value.email) {
        callback(new Error('联系电话和邮箱至少填写一项'))
      } else {
        callback()
      }
    }
    
    const customerFormRules = {
      name: [
        { required: true, message: '请输入客户姓名', trigger: 'blur' },
        { min: 2, max: 50, message: '客户姓名长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      companyName: [
        { required: true, message: '请输入公司名称', trigger: 'blur' },
        { min: 2, max: 100, message: '公司名称长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      phone: [
        { validator: validateContact, trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { validator: validateContact, trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择客户状态', trigger: 'change' }
      ]
    }
    
    const dialogTitle = computed(() => {
      return isEdit.value ? '编辑客户' : '新增客户'
    })
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      switch (status) {
        case '潜在客户': return ''
        case '已联系客户': return 'success'
        case '已流失': return 'danger'
        default: return 'info'
      }
    }
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return ''
      return new Date(dateTime).toLocaleString('zh-CN')
    }
    
    // 加载客户列表
    const loadCustomers = async () => {
      customersLoading.value = true
      try {
        const params = {
          page: pagination.value.page,
          size: pagination.value.size
        }
        if (queryForm.value.status) {
          params.status = queryForm.value.status
        }
        if (queryForm.value.keyword) {
          params.keyword = queryForm.value.keyword
        }
        
        const response = await getCustomerList(params)
        if (response.data.code === 200) {
          const data = response.data.data
          customers.value = data.records || data
          pagination.value.total = data.total || customers.value.length
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('获取客户列表失败')
      } finally {
        customersLoading.value = false
      }
    }
    
    // 查询功能
    const handleSearch = () => {
      pagination.value.page = 1
      loadCustomers()
    }
    
    // 重置查询
    const handleReset = () => {
      queryForm.value.status = ''
      queryForm.value.keyword = ''
      pagination.value.page = 1
      loadCustomers()
    }
    
    // 分页大小改变
    const handleSizeChange = (newSize) => {
      pagination.value.size = newSize
      pagination.value.page = 1
      loadCustomers()
    }
    
    // 当前页改变
    const handleCurrentChange = (newPage) => {
      pagination.value.page = newPage
      loadCustomers()
    }
    
    // 新增客户
    const handleAdd = () => {
      isEdit.value = false
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑客户
    const handleEdit = (row) => {
      isEdit.value = true
      customerForm.value = {
        id: row.id,
        name: row.name,
        companyName: row.companyName,
        phone: row.phone,
        email: row.email,
        status: row.status,
        source: row.source,
        remark: row.remark
      }
      dialogVisible.value = true
    }
    
    // 删除客户
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(`确定要删除客户 ${row.name} 吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await deleteCustomer(row.id)
        if (response.data.code === 200) {
          ElMessage.success('删除成功')
          loadCustomers() // 重新加载列表
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!customerFormRef.value) return
      
      try {
        await customerFormRef.value.validate()
        submitLoading.value = true
        
        let response
        if (isEdit.value) {
          // 编辑客户
          response = await updateCustomer(customerForm.value.id, customerForm.value)
        } else {
          // 新增客户
          response = await createCustomer(customerForm.value)
        }
        
        if (response.data.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
          dialogVisible.value = false
          loadCustomers() // 重新加载列表
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 重置表单
    const resetForm = () => {
      customerForm.value = {
        id: null,
        name: '',
        companyName: '',
        phone: '',
        email: '',
        status: '',
        source: '',
        remark: ''
      }
      if (customerFormRef.value) {
        customerFormRef.value.resetFields()
      }
    }
    
    onMounted(() => {
      loadCustomers()
    })
    
    return {
      customers,
      customersLoading,
      dialogVisible,
      submitLoading,
      customerForm,
      customerFormRules,
      customerFormRef,
      queryForm,
      pagination,
      tableHeight,
      dialogTitle,
      getStatusTagType,
      formatDateTime,
      loadCustomers,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleDelete,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>